package com.cq.hd.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import lombok.extern.slf4j.Slf4j;

import java.util.Calendar;
import java.util.Date;

/**
 * @description: Jwt工具类
 * @author: mYunYu
 * @date: 2021/7/7 16:21
 * @version: v1.0
 */
@Slf4j
public class JwtUtil {
    /**
     * 过期时间
     */
    public static final int CALENDAR_INTERVAL = 60 * 24 * 365;

    /**
     * 时间单位
     */
    public static final int CALENDAR_FIELD = Calendar.MINUTE;

    /**
     * @Description: 获取token
     * @Param: [info 保存信息 secret 选择签名加密算法]
     * @Return: java.lang.String
     * @Auther: mYunYu
     * @Date: 2021/7/7 16:21
     */
    public static String createToken(String secret, String... info) {
        Calendar time = Calendar.getInstance();
        time.add(CALENDAR_FIELD, CALENDAR_INTERVAL);
        Date expireTime = time.getTime();
        return JWT.create().withExpiresAt(expireTime).withAudience(info).sign(Algorithm.HMAC256(secret));
    }

    /**
     * @Description: 指定过期时间获取token
     * @Param: [info 保存信息 secret 选择签名加密算法 expiresAt 过期时间]
     * @Return: java.lang.String
     * @Auther: mYunYu
     * @Date: 2021/7/7 16:22
     */
    public static String createToken(String info, String secret, Date expiresAt) {
        return JWT.create().withExpiresAt(expiresAt).withAudience(info).sign(Algorithm.HMAC256(secret));
    }

    /**
     * @Description: 获取保存在Audience中的第一条信息
     * @Param: [token, index]
     * @Return: java.lang.String
     * @Auther: mYunYu
     * @Date: 2021/7/7 16:22
     */
    public static String getAudience(String token, int index) {
        return JWT.decode(token).getAudience().get(index);
    }

    /**
     * @Description: 验证token
     * @Param: [token, secret]
     * @Return: boolean
     * @Auther: mYunYu
     * @Date: 2021/7/7 16:22
     */
    public static boolean tokenVerify(String token, String secret) {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
        try {
            jwtVerifier.verify(token);
            return true;
        } catch (JWTVerificationException e) {
            log.error("验证token失败");
        }
        return false;
    }

    public static void main(String[] args) {
        log.info("生成token:" + createToken("94680628", "4", "1"));
    }
}